package com.example.train_operate.util;

import okhttp3.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpRequest {

    private final OkHttpClient client;

    public OkHttpRequest(){
        client = new OkHttpClient().newBuilder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 同步http请求
     */
    public String sendRequestSync(String url,
                                  String method,
                                  Map<String, String> headers,
                                  String requestBody,
                                  Map<String, String> queryParams){
        //如果请求是GET或者DELETE请求且有请求参数，则构造带参的url
        if((method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("DELETE"))
        && queryParams != null && !queryParams.isEmpty()){
            //拼接url地址
            url = buildUrlWithParams(url, queryParams);
        }
        //创建请求体
        RequestBody body = null;
        if(requestBody != null && !requestBody.isEmpty() &&
            !method.equalsIgnoreCase("GET") && !method.equalsIgnoreCase("DELETE")){
            body = RequestBody.create(
                    requestBody,
                    MediaType.parse("application/json; charset=utf-8")
            );
        }
        //构造请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url);
        //设置请求头
        if(headers != null){
            for(Map.Entry<String, String> entry : headers.entrySet()){
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        //设置请求方法
        switch (method.toUpperCase()){
            case "POST":
                requestBuilder.post(body);
                break;
            case "PUT":
                requestBuilder.put(body);
                break;
            case "DELETE":
                requestBuilder.delete(body != null ? body : RequestBody.create(new byte[0]));
                break;
            default:
                requestBuilder.get();
                break;
        }
        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()){
            if(!response.isSuccessful()){
                throw new IOException("请求失败，状态码：" + response.code()
                        + "，消息：" + response.message());
            }
            ResponseBody responseBody = response.body();
            return responseBody.string();
        }catch (IOException e){
            throw new RuntimeException("请求失败：" + e);
        }
    }


    /**
     * 构造带参数的url
     */
    private static String buildUrlWithParams(String baseUrl, Map<String, String> params){
        if(params == null || params.isEmpty()){
            return baseUrl;
        }
        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        boolean firstParam = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if(firstParam){
                urlBuilder.append("?");
                firstParam = false;
            } else {
                urlBuilder.append("&");
            }
            //URL编码参数
            String encodeKey = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8);
            String encodeValue = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8);
            urlBuilder.append(encodeKey).append("=").append(encodeValue);
        }
        return urlBuilder.toString();
    }
}
